package com.scau.database.enums;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回   "enum": {"code": "2","message": "tom2"} 格式给前端
 */
@Slf4j
public class JsonEnumSerializer extends JsonSerializer<BaseEnum> {
    @Override
    public void serialize(BaseEnum value, JsonGenerator gen, SerializerProvider serializers) {
        try {
            //类的code值
            Object type = value.getType();

            String description = value.getDescription();

            //这里也不用反射了,性能不好,所以直接new一个map再做序列化
            Map<String, Object> jsonMap = new HashMap<>(2);
            jsonMap.put("type", type);
            jsonMap.put("description", description);

            serializers.defaultSerializeValue(jsonMap, gen);
        } catch (Exception e) {
            log.error("JsonEnumSerializer serialize error", e);
            throw new RuntimeException(e);
        }
    }
}